from Netease_cloud_translated_lyrics import *
import re

time_tag = []
lyric_dict = {}
lines = []
def lrc_to_dict():
    global lines
    global time_tag
    global lyric_dict

    def deal_with_lines(lines1):
        time_tag = []
    # 去空行
        for kong in lines1:
            if kong == '\n':
                lines1.remove(kong)

        key_word = ['.by:.+\\n']
        for a in key_word:
            for i in lines1:
                rs = re.findall(a, i)
                if rs != []:
                    print(rs)
                    lines1.remove(rs[0])

        for i in lines1:
            i = i[0:6]+ ',' +i[7:]
            lines.append(i)


        #生成字典
        if lines[0][9] == ']':
            index = 9
        else:
            index = 10
        lyric_dict = {lines[i][1:index]:lines[i][index+1:] for i in range(len(lines))}

        #get_time_tag():
        for i in lines:
            time_tag.append(i[1:index])

        return time_tag, lyric_dict


    with open(f'./{song_info}/{song_info}.lrc', 'r', encoding='utf8') as f:
        lines1 = f.readlines()
        time_tag1, lyric_dict1 = deal_with_lines(lines1)

    with open(f'./{song_info}/{song_info}_translated.lrc', 'r', encoding='utf8') as f:
        lines2 = f.readlines()
        time_tag2, lyric_dict2 = deal_with_lines(lines2)

    return time_tag1, lyric_dict1, lyric_dict2



def get_srt(time_tag1, lyric_dict1, lyric_dict2, end_time):
    print(time_tag1)
    with open(f'./{song_info}/{song_info}.srt', 'w', encoding='utf8') as f:

        for num in range(len(time_tag1)):
            if num == len(time_tag1)-1:
                f.write(f'{num + 1}\n')
                f.write(f'{time_tag1[num]} --> {end_time}\n')
                f.write(f'{lyric_dict1[time_tag1[num]]}')
                try:
                    f.write(f'{lyric_dict2[time_tag1[num]]}')
                except:
                    pass
                finally:
                    f.write('\n')
                break

            f.write(f'{num+1}\n')
            f.write(f'{time_tag1[num]} --> {time_tag1[num+1]}\n')
            f.write(f'{lyric_dict1[time_tag1[num]]}')
            try:
               f.write(f'{lyric_dict2[time_tag1[num]]}')
            except:
                pass
            finally:
                    f.write('\n')
                


if __name__ == '__main__':
    flag = int(input('是否要下载歌词(1为下载)'))
    song_info = input('歌曲信息')
    if flag == 1:
        song_id = input('网易云歌曲id：')  # 1398628590
        lyric = translated_lyrics()
        lyric.run_lyric(song_id, song_info)
    time_tag1, lyric_dict1, lyric_dict2 = lrc_to_dict()
    end_time = input('结束时间：格式示范（03:40,398）') #02:40,373
    get_srt(time_tag1, lyric_dict1, lyric_dict2, end_time)

